# -*- coding: UTF-8 -*-
from app import app
from flask import jsonify,request

import pymongo
import requests
import re
import json

@app.route('/getavgbyqu')
def getavgbyqu():
    connection = pymongo.MongoClient('139.224.135.121', 27017)
    db = connection.lianjia
    db.authenticate("developer", "qwerqwer")
    ershoufang = db.ershoufang
    aggs = [
        {"$group": {"_id": "$qu", "avg": {"$avg": "$price"}}},
    ]

    cursor = ershoufang.aggregate(pipeline=aggs)
    result = []
    for i in cursor:
        result.append(i)
    return jsonify(result)

@app.route('/getallprice', methods=['GET', 'POST'])
def getallprice():
    data = request.get_json(silent=False)
    connection = pymongo.MongoClient('139.224.135.121', 27017)
    db = connection.lianjia
    db.authenticate("developer", "qwerqwer")
    ershoufang = db.ershoufang
    cursor = ershoufang.find().limit(200).skip(data['page']*200 -200)
    result = []
    for i in cursor:
        try:
            tmp = {}
            tmp['lng'] = float(i['lng'])
            tmp['lat'] = float(i['lat'])
            tmp['count'] = i['price']/1000
            result.append(tmp)
        except:
            print("catched a exception")
    return jsonify(result)

@app.route('/getprice/distance')
def distance () :
    connection = pymongo.MongoClient('139.224.135.121', 27017)
    db = connection.mydb
    db.authenticate("diamond", "qwerqwer")
    ershoufang = db.ShDeal
    cursor = ershoufang.find().limit(500)
    result = []
    for i in cursor:
        try :
            if i['distance'] < 40000:
                result.append([i['distance'],float(i['price'])])
        except :
            print("no distance")
    return jsonify(result)

@app.route('/getprice/duration')
def duration () :
    connection = pymongo.MongoClient('139.224.135.121', 27017)
    db = connection.mydb
    db.authenticate("diamond", "qwerqwer")
    ershoufang = db.ShDeal
    cursor = ershoufang.find().limit(500)
    result = []
    for i in cursor:
        try :
            if i['duration'] < 4000:
                result.append([i['duration'],float(i['price'])])
        except :
            print("no duration")
    return jsonify(result)

@app.route('/estimate', methods=['GET', 'POST'])
def estimate () :
        return '{\"success\": true, \"price\": 100000}'
